package com.thz.friend.rabbit.consumer;

import com.thz.common.core.constants.RabbitConstants;
import com.thz.friend.pojo.user.dto.UserDTO;
import com.thz.mail.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author thz
 * @Date 2025/3/16
 */
@Slf4j
@Component
public class MailConsumer {
    @Autowired
    private MailUtil mailUtil;

    @Value("${spring.mail.properties.subject}")
    private String subject;

    @Value("${sms.code-expiration:5}")
    private Long emailCodeExpiration;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = RabbitConstants.OJ_MAIL_QUEUE , durable = "true"),
            exchange = @Exchange(value = RabbitConstants.OJ_MAIL_EXCHANGE , type = ExchangeTypes.FANOUT),
            key = {RabbitConstants.OJ_MAIL_KEY}
    ))
    public void handler(UserDTO userEmailSendDTO) {
        try {
            mailUtil.sendMail(userEmailSendDTO.getEmail(),subject,buildContent(userEmailSendDTO.getCode()));
        }catch (Exception e){
            log.error("邮件发送失败, e:", e);
        }
    }

    private String buildContent(String code){
        return "<br>" + "您的验证码为" + code + "。" + emailCodeExpiration + "分钟内有效，请勿泄露和转发。如非本人操作，请忽略此短信" + "<br/>";
    }
}
